import { request } from 'umi';
import axios from "axios";

const ROOT = '/cpasApi';

export enum BatchOperationType {
  DATA_RECALCULATE = "dr",  //  数据批量重算
  VERIFY_RECALCULATE = "vr", // 勾稽重算
  VERIFY_STATISTICS  = "vs",  //勾稽重算,带有统计信息
  DATA_VERIFY_RECALCULATE = "dvr" // 批量重算,勾稽重算组合.不需要勾稽信息
}

// 报表注释与分析 - 披露表 - methodAPI - 固定资产 接口
async function getDisclosureApiData(name: string, dbName: string, data_id: string): Promise<API.SerResult> {
  const pd: API.Disclosure = {
    name: name,// 接口名
    dbName: dbName, //数据库名
    data_id: data_id, // 年度
  };

  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/getDisclosureApiData`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: pd,
    });

    if (res.code !== 0) {

      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 披露表 - 企业基础数据 取数源接口  GET
async function getCorpDataSrcMenu() {
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/getCorpDataSrcMenu`, {
      method: "GET",
      headers: {
        'Content-Type': 'application/json',
      },
    });
    if (res.code !== 0) {

    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// // 披露表 - 底稿结构化数据 报表项目 接口 POST /disclosure/getReportItemMenu
async function getReportItemMenu() {
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/getReportItemMenu`, {
      method: "GET",
      headers: {
        'Content-Type': 'application/json',
      },
    })
    if (res.code !== 0) {

    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 披露表 - 底稿结构化数据 取数源 接口 POST
async function getReportDataSrcMenu(item: string) {
  // "reportItem": "固定资产"
  const pd: API.reportStructSel = {
    reportItem: item
  }
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/getReportDataSrcMenu`, {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
      },
      data: pd,
    });
    if (res.code !== 0) {

    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

/**
 * 保存设计表
 * @param dbname
 * @param templateName
 * @param tableNames
 * @param type
 * @param dateId
 * @param action
 * @param mode
 * @param tids
 */
export const singleDSTableInit = async (
  dbname: any,
  templateName: string,
  tableNames: string[],
  type: string,
  dateId: any
) => {
  try {
    const response = await axios.post(`${ROOT}/template/importTemplate`, {
      dbName: dbname,
      type,
      templateName,
      tableNames,
      dataId: dateId,
      action: "initOne",
      opt: {
        duplicate: "cover"
      }
    });
    return response.data;
  } catch (e) {
    throw e;
  }
}

// export const singleDSTableInit = async (
//   dbname: any,
//   templateName: string,
//   tableNames: string[],
//   type: string,
//   dateId: any,
//   action: any,
//   mode: any,
//   items: any
// ) => {
//   try {
//     const response = await axios.post(`${ROOT}/template/importTemplate`, {
//       dbname,
//       type,
//       templateName,
//       tableNames,
//       dateId,
//       action,
//       mode,
//       items
//     });
//     return response.data;
//   } catch (e) {
//     throw e;
//   }
// }

/**
 * 从模板中查询数据
 */
export const queryCpasTableByMb = async (
  dbname: any,
  templateName: string,
  tableNames: string[],
  type: string
) => {
  try {
    const response = await axios.post(`${ROOT}/template/getTemplateTablesInfo`, {
      dbname,
      type,
      templateName,
      tableNames,
    });
    return response.data;
  } catch (e) {
    throw e;
  }
};


// 左侧树
// 获取树节点列表  GET /disclosure/notes
async function getLeftTrees(dbName: string, dataId: any) {
  const params: API.getTree = {
    dbName: dbName,
    dataId: dataId
  }
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/notes`, {
      method: "GET",
      headers: {
        'Content-Type': 'application/json',
      },
      params: params,
    });
    if (res.code !== 0) {
      console.log('获取树节点列表', res)
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 查询空披露表接口  GET /disclosure/notes-is-empty
async function notesIsEmpty(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/notes-is-empty`, {
      method: "GET",
      headers: {
        'Content-Type': 'application/json',
      },
      params: params,
    });
    if (res.code !== 0) {
      console.log('查询空披露表', res)
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 新建树节点 POST
async function addTreeNode(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/notes`, {
      method: "POST",
      // headers: {
      //     'Content-Type': 'application/json',
      //   },
      data: params
    });
    console.log(res);

    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// 树节点调整
async function moveTreeNode(params: any, id: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/notes/adjust/${id}`, {
      method: "PUT",
      headers: {
        'Content-Type': 'application/json',
      },
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 左侧树删除节点 DELETE
async function delTreeNode(id: string, dbName: string) {
  const params: API.delTreeNode = {
    dbName: dbName
  }
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/notes/` + id, {
      method: "Delete",
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      console.log('---', res)
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 批量常在界面展示
async function alwaysShow(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/always-show`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 左侧修改树节点 edit
async function editTreeNode(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/notes/${params.id}`, {
      method: "PUT",
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 获取报表项目列表
async function getReportList(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/disclosure/notes/report-items?dbName=${params.dbName}&year=${params.year}`, {
      method: "GET",
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 检测节点是否重名
async function checkCpasTableName(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/getCpasTableByName`, {
      method: "GET",
      params
    })
    return res
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }

}

// 修该cpsa table
async function editCpasTableName(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/renameCpasTable`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 粘贴
async function copyCpasTable(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/getCpasTableByTid`, {
      method: "GET",
      params
    });
    return res
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 根据tids查询cpastable数据
async function getCpasTableByTidsApi(params: {
  dbname: string,
  tids: any,
  type: string,
  dataType: string,
  isToZl: boolean,
  dataGridType?: string
}) {
  try {
    const response = await axios.post(`${ROOT}/cpasTableEngine/getCpasTableByTids`, {
     ...params
    });
    return response.data;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

async function queryState(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableOperation/getOperationState`, {
      method: "GET",
      params
    });
    return res
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// 删除勾稽校验
// async function removeVerifyData(params: any) {
//   try {
//     const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/removeVerifyDataByTid`, {
//       method: "POST",
//       data: params
//     })
//     return res
//   } catch (error) {
//     return Promise.resolve({ data: error, ok: false, code: 100000 });
//   }
// }


export const getTemplateInfo = async (zcbfid: string) => {
  try {
    const { data } = await axios.post(
      `${ROOT}/sqlapis/getApiData?api=account.seekAuditReportTemplate`,
      {
        name: "account.seekAuditReportTemplate",
        params: {
          zcbfid: zcbfid,
        },
      }
    );
    return data;
  } catch (e) {
    return Promise.resolve({ data: e, ok: false, code: 100000 });
  }
};

// 勾稽汇总的重算
async function getAllVerifyData(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableOperation/batchVerifyRecalculate`, {
      method: "POST",
      data: {
        ...params,
        type:BatchOperationType.VERIFY_STATISTICS
      }
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

async function getAllVerifyTypeData(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableOperation/batchVerifyRecalculate`, {
      method: "POST",
      data: {
        ...params,
      }
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 附注节点批量重算
export async function reCalculateNotes(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableOperation/batchDataAndVerifyRecalculate`, {
      method: "POST",
      // headers: {
      //     'Content-Type': 'application/json',
      //   },
      data: {
        ...params,
        type:BatchOperationType.DATA_VERIFY_RECALCULATE
      }
    });
    console.log(res);
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

async function removeDataAll(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableOperation/batchClearCpasTableData`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
/**
 * 批量清空公式 0510
 * @param params
 * @returns
 */
async function removeFormulaAll(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableOperation/batchClearFormulas`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}


async function resetQueryState(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableOperation/updateOperationState`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
async function queryVerifyState(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/getVerifyResult`, {
      method: "GET",
      params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// 导入
async function templateExport(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/template/exportData`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// 保存模版
async function templateExportToSqlite(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/template/exportDataToSqlite`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// 导出
async function templateImport(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/template/importTemplate`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
/*从外部模板文件中查询NotesTree列表
GET /template/getNotesTreeListNew
接口ID：99961872
接口地址：https://app.apifox.com/project/1267497/apis/api-99961872*/
async function templateForNotesTreeList(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/template/getNotesTreeListNew`, {
      method: "GET",
      params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// 批量断开和恢复
async function batchFormula(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableOperation/batchOpenOrCloseFormula`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 批量 导出 excel
async function templateExportExcel(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/getCpatableToBatchExportExcel`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// 查询任意文件夹下有没有存在的文件
async function isHaveTemplateDB(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/template/queryAnyFileIfExistInDisk`, {
      method: "GET",
      params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

export async function getReportItemsZero(params: { partId: string, dataId: string }) {
  const data = await request(
    `/cpasApi/disclosure/report-items-zero?dbName=${params.partId}&dataId=${params.dataId}`,
    {
      method: 'GET',
    },
  );
  return data;
}

// 根据附注顶级节点及子节点查询所在整理模式的数据并批量导出excel
async function getNotesTreeZLToExportExcel(params: any) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/batchExportExcelResult`, {
      method: "POST",
      data: params
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// excel批量导入且执行列匹配操作
async function importExcelToColumnMatch(params: {
  filePath: string,
  dbname: string,
  type: string, // ds||fs
  dataId: string;
}) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/importExcelToColumnMatch`, {
      method: "POST",
      data: params
    });
    return res.data;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 保存excel批量导入数据入库
async function saveImportExcel(params: {
  dbname: string,
  type: string, // ds||fs
  dataId: string,
  manualColumnsIndex?: any,
}) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/saveExcelImport`, {
      method: "POST",
      data: params
    });
    return res.data;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

interface excelCfgData {
  cmapColumnCmapData: any,//提取excel的cmap数据
  hmCfgData: any //提取excel的豁免单元格配置
}
interface systemCfgData {
  headerColumn: any,//经过headSerice转换过后的列
  data: any //系统cpastable表数据
}
/**自动匹配excel列和系统列,返回双方列的对应关系
 *
 * @param params
 * @returns
 */
async function autoMathExcelToSystem(params: {
  excelCfg: excelCfgData,
  cpasCfg: systemCfgData,
  dbname: string,
}) {
  try {
    const res = await request<API.SerResult>(`${ROOT}/cpasTableEngine/autoMathExcelToSystem`, {
      method: "POST",
      data: params
    });
    return res.data;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
export {
  getDisclosureApiData,
  getCorpDataSrcMenu,
  getReportDataSrcMenu,
  getReportItemMenu,
  getLeftTrees,
  addTreeNode,
  delTreeNode,
  editTreeNode,
  moveTreeNode,
  getReportList,
  checkCpasTableName,
  editCpasTableName,
  copyCpasTable,
  queryVerifyState,
  // removeVerifyData,
  removeDataAll,
  getAllVerifyData,
  queryState,
  resetQueryState,
  templateExport,
  templateImport,
  batchFormula,
  templateExportExcel,
  isHaveTemplateDB,
  templateForNotesTreeList,
  alwaysShow,
  templateExportToSqlite,
  notesIsEmpty,
  getAllVerifyTypeData,
  getNotesTreeZLToExportExcel,
  getCpasTableByTidsApi,
  importExcelToColumnMatch,
  saveImportExcel,
  autoMathExcelToSystem,
  removeFormulaAll
};
